// pages/sweeping.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        lv: 0, //等级,0,1,2
		gameLvs : [ "1", "2", "3" ],
		sizes : [ 9, 13, 19 ], //不同等级的桌面大小
		thunders : [ 16, 32, 64 ], //不同等级的雷的数量

		//重新开始时,需要重置这些值 -begin
		markNum : 0, //被标记数
		trueMarkThunderNum : 0, //被标记的真正的雷的数量
		openNum : 0, //被点开的
        times : 0, //计时
        over: true, // 是否结束了
        //重新开始时,需要重置这些值 -end
        
		thundersArr : [], //记录雷的位置
		timer : null, //计时器
        
		ths : [] //作弊
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // this.start();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.doContinueGame();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.doStopGame();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    start() {
        let lv = this.data.lv;
        //let sizes = this.data.sizes;
        let thunders = this.data.thunders;

        if(this.data.timer) {
            clearInterval(this.data.timer);//停止计时器
        }

        this.initTableArr();
        this.setThunder(thunders[lv]);

        this.initTable();

        this.setData({
            //重新开始时,需要重置这些值 -begin
            markNum : 0, //被标记数
            trueMarkThunderNum : 0, //被标记的真正的雷的数量
            openNum : 0, //被点开的
            times : 0, //计时
            over : false, 
            //重新开始时,需要重置这些值 -end
            
            thundersArr : this.data.thundersArr, //记录雷的位置
            lv: lv
        });

        this.data.timer = setInterval(() => {
            this.data.times++;
            this.setData({
                times: this.data.times
            });
        }, 1000);
    },
    initTableArr() {
        let lv = this.data.lv;
        let sizes = this.data.sizes;
        let thundersArr = [];
        for(let i=0; i<sizes[lv]; i++){
            thundersArr[i] = new Array();
            for(let j=0; j<sizes[lv]; j++){
                thundersArr[i][j] = {
                    isOpen: false, count: 0, has: false, isMark: false,
                    icon: '',
                    x: i, y: j
                };
            }
        }
        this.data.thundersArr = thundersArr;
    },
    setThunder(count){
        let lv = this.data.lv;
        let sizes = this.data.sizes;
        let thundersArr = this.data.thundersArr;
        //let ths = this.data.ths;

        let size = sizes[lv];//桌面尺寸
        for(let i=0; i<count; i++){
            let has = true;//当前位置有地雷
            while(has){//有,生成新的位置坐标
                // -2 + 1 是 设置四边无雷, 降低难度
                let x = this.random(size - 2) + 1;
                let y = this.random(size - 2) + 1;
                has = thundersArr[x][y].has;
                if(!has){//没有,放到当前位置坐标
                    thundersArr[x][y].has = true;
                    //ths.push({x: x, y: y});
                }
            }
        }
        // ths.sort(function(a, b){
        //     if(a.x == b.x){
        //         return a.y - b.y;
        //     }
        //     return a.x - b.x;
        // })
        //console.log('thunders:', ths);
    },
    initTable() {
        let lv = this.data.lv;
        let sizes = this.data.sizes;
        let thundersArr = this.data.thundersArr;

        for (let i = 0; i < sizes[lv]; i++) {
            for (let j = 0; j < sizes[lv]; j++) {
                let isThunder = thundersArr[i][j].has;
                //不是雷则,计算四周的地雷数量
                if(!isThunder){
                    let counts = this.countAroundThunders(i, j);
                    thundersArr[i][j].count = counts;
                    thundersArr[i][j].countTxt = counts ? counts : "";
                }
            }
        }
    },
    countAroundThunders(x, y) {
        let lv = this.data.lv;
        let sizes = this.data.sizes;
        let thundersArr = this.data.thundersArr;
        //边界
        let begin = 0;
        let end = sizes[lv];
        let count = 0;
        //xy
        //00  01  02
        //10 (11) 12
        //20  21  22
        //八个位置
        //上
        if((x - 1) >= begin){
            let isThunder = thundersArr[x - 1][y].has;
            if(isThunder){
                count++;
            }
        }
        //右上
        if((x - 1) >= begin && (y + 1) < end){
            let isThunder = thundersArr[x - 1][y + 1].has;
            if(isThunder){
                count++;
            }
        }
        //右
        if((y + 1) < end){
            let isThunder = thundersArr[x][y + 1].has;
            if(isThunder){
                count++;
            }
        }
        //右下
        if((x + 1) < end && (y + 1) < end){
            let isThunder = thundersArr[x + 1][y + 1].has;
            if(isThunder){
                count++;
            }
        }
        //下
        if((x + 1) < end){
            let isThunder = thundersArr[x + 1][y].has;
            if(isThunder){
                count++;
            }
        }
        //左下
        if((x + 1) < end && (y - 1) >= begin){
            let isThunder = thundersArr[x + 1][y - 1].has;
            if(isThunder){
                count++;
            }
        }
        //左
        if((y - 1) >= begin){
            let isThunder = thundersArr[x][y - 1].has;
            if(isThunder){
                count++;
            }
        }
        //左上
        if((x - 1) >= begin && (y - 1) >= begin){
            let isThunder = thundersArr[x - 1][y - 1].has;
            if(isThunder){
                count++;
            }
        }
        return count;
    },
    autoClearZero(x, y, tips){
        let lv = this.data.lv;
        //显示"0"方块的周围连续的方块(未打开的,不是雷的方块)
        let sizes = this.data.sizes;

        //边界
        let begin = 0;
        let end = sizes[lv];
        // x = parseInt(x);
        // y = parseInt(y);
        //xy
        //00  01  02
        //10 (11) 12
        //20  21  22
        //八个位置
        //上
        if((x - 1) >= begin){
            this.doAutoOpen(x - 1, y, tips);
        }
        //右上
        if((x - 1) >= begin && (y + 1) < end){
            this.doAutoOpen(x - 1, y + 1, tips);
        }
        //右
        if((y + 1) < end){
            this.doAutoOpen(x, y + 1, tips);
        }
        //右下
        if((x + 1) < end && (y + 1) < end){
            this.doAutoOpen(x + 1, y + 1, tips);
        }
        //下
        if((x + 1) < end){
            this.doAutoOpen(x + 1, y, tips);
        }
        //左下
        if((x + 1) < end && (y - 1) >= begin){
            this.doAutoOpen(x + 1, y - 1, tips);
        }
        //左
        if((y - 1) >= begin){
            this.doAutoOpen(x, y - 1, tips);
        }
        //左上
        if((x - 1) >= begin && (y - 1) >= begin){
            this.doAutoOpen(x - 1, y - 1, tips);
        }
    },
    doAutoOpen(x, y, tips) {//打开可以显示的
        // let lv = this.data.lv;
        // let sizes = this.data.sizes;
        let thundersArr = this.data.thundersArr;

        //console.log('doAutoOpen:', x, y);
        
        let td = thundersArr[x][y];
        let isThunder = td.has;
        let isOpen = td.isOpen;
        //if(tips && !isOpen){//是提示, 且没有被点过
            // 添加提示样式
            //return;
        //}
        //没有被点击过,且不是雷
        if(!isOpen && !isThunder){
            //打开
            td.isOpen = true;
            //target.removeClass('closed');
            //target.addClass('opened' + td.count);
            if(0 != td.count){
                //target.text(td.count);
            }
            this.data.openNum++;
            if(0 == td.count){
                this.autoClearZero(x, y);
            }
        }
    },
    showTips(x, y) {
        let thundersArr = this.data.thundersArr;

        this.autoClearZero(x, y, true);

        let td = thundersArr[x][y];
        //let target = $('td[x='+ x +'][y='+ y +']');
        if(!td.isOpen){
            //$(target).addClass('tips');
        }
    },
    random(len){
        let num = parseInt(Math.random() * len);
        //console.log("num=", num);
        return num;
    },
    doTouchOpen(event) {
        //console.log('doTouchOpen:', event);
        let td = event.target.dataset.td;
        if(!td || td.isOpen || this.data.timer === null){
            return;
        }
        //console.log(td);
        let cell = this.data.thundersArr[td.x][td.y];
        if(cell.isMark) return;
        if(cell.has) {
            cell.icon = 'thunder-icon';
            this.setData({
                thundersArr: this.data.thundersArr
            });
            clearInterval(this.data.timer);//停止计时器
            this.data.timer = null;
            this.data.over = true;

            wx.showToast({
                title: '点到炸弹了！',
                icon: "none"
            });

            wx.showModal({
                title: '提示',
                content: 'You lose, restart?',
                success: (res) => {
                    if (res.confirm) {
                        wx.showToast({
                            title: 'start',
                            icon: "success"
                        });
                        this.start();
                    } else if (res.cancel) {
                        //console.log('用户点击取消');
                    }
                }
            });
        } else {
            cell.isOpen = true;
            this.data.openNum++;
            if(!cell.has && cell.count == 0) {
                this.autoClearZero(cell.x, cell.y);
            }
            this.setData({
                thundersArr: this.data.thundersArr
            });

            this.isWin();
        }
    },
    doTouchMark(event) {
        //console.log('doTouchMark:', event);
        let td = event.target.dataset.td;
        if(!td || td.isOpen || this.data.timer === null){
            return;
        }
        let markNum = this.data.markNum;
        let cell = this.data.thundersArr[td.x][td.y];
        cell.isMark = !cell.isMark;
        if(cell.isMark) {
            markNum++;
            if(cell.has) this.data.trueMarkThunderNum++;
            cell.icon = 'mark-icon';
            this.setData({
                thundersArr: this.data.thundersArr,
                markNum: markNum
            });
            this.isWin();
        } else {
            markNum--;
            if(cell.has) this.data.trueMarkThunderNum--;
            cell.icon = '';
            this.setData({
                thundersArr: this.data.thundersArr,
                markNum: markNum
            });
        }
    },
    isWin() {
        let markNum = this.data.markNum;
        let openNum = this.data.openNum;
        let sizes = this.data.sizes;
        let lv = this.data.lv;
        let thunders = this.data.thunders;
        if(thunders[lv] == this.data.trueMarkThunderNum || (openNum + this.data.trueMarkThunderNum + thunders[lv] - markNum ) == (sizes[lv] * sizes[lv])){
            // you win
            clearInterval(this.data.timer);//停止计时器
            this.data.timer = null;
            this.data.over = true;

            wx.showModal({
                title: '提示',
                content: 'You Win, restart?',
                success: (res) => {
                    if (res.confirm) {
                        wx.showToast({
                            title: 'start',
                            icon: "success"
                        });
                        this.start();
                    } else if (res.cancel) {
                        //console.log('用户点击取消');
                    }
                }
            });
            return true;
        }
        return false;
    },
    doReStartGame() {
        wx.showToast({
            title: '开始',
            icon: "success"
        });
        this.start();
    },
    doStopGame() {
        if(this.data.timer) {
            clearInterval(this.data.timer);
            this.data.timer = null;
            wx.showToast({
                title: '暂停',
                icon: "success"
            });
        }
    },
    doContinueGame() {
        if(this.data.over || this.data.timer) {
            return;
        }
        wx.showToast({
            title: '继续',
            icon: "success"
        });
        this.data.timer = setInterval(() => {
            this.data.times++;
            this.setData({
                times: this.data.times
            });
        }, 1000);
    },
    doChangeGameLv(e) {
        this.data.lv = e.detail.value;
        //console.log(e.detail.value);
        this.doReStartGame();
    }
})